import { defineStore } from "pinia";
import {
  getAccessToken,
  setAccessToken,
  removeAccessToken,
} from "@/utils/accessToken";
import setting from "@/config/setting.config";
import { message, notification } from "ant-design-vue";
import { login } from "@/api/user";
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
const title = import.meta.env.VITE_VUE_APP_TITLE;
const { tokenName } = setting;
export const useStore = defineStore("login", {
  state() {
    return {
      userInfo: {},
      accessToken: getAccessToken(),
      admin: false,
      role: [],
      ability: [],
    };
  },
  getters: {
    userId() {
      return this.userInfo.id || "xxx";
    },
    getAccessToken() {
      return this.accessToken;
    },
    getAdmin() {
      return this.admin;
    },
    getRole() {
      return this.role;
    },
    getAbility() {
      return this.ability;
    },
  },
  actions: {
    setFull(admin) {
      this.admin = admin;
    },
    setRole(role) {
      this.role = role;
    },
    setAbility(ability) {
      this.ability = ability;
    },
    /**
     * @description 设置token
     */
    setAccessToken(accessToken) {
      this.accessToken = accessToken;
      setAccessToken(accessToken);
    },
    async login(userInfo) {
      // const { data } = await login(userInfo);
      // const accessToken = data[tokenName];
      if ('1111') {
        // commit('setAccessToken', accessToken)
        this.setAccessToken('111111');
        const hour = new Date().getHours();
        const thisTime =
          hour < 8
            ? "早上好"
            : hour <= 11
            ? "上午好"
            : hour <= 13
            ? "中午好"
            : hour < 18
            ? "下午好"
            : "晚上好";
        notification.open({
          message: `欢迎登录${title}`,
          description: `${thisTime}！`,
        });
      } else {
        message.error(`登录接口异常，未正确返回${tokenName}...`);
      }
    },
    /**
     * @description 退出登录
     */
    async logout() {
      // await logout(state.accessToken)
      await this.resetAll();
    },
    /**
     * @description 重置accessToken、roles、ability、router等
     */
    async resetAll() {
      this.setAccessToken("");
      this.setFull(false, { root: true });
      this.setRole([], { root: true });
      this.setAbility([], { root: true });
      removeAccessToken();
    },
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo };
    },
  },
});
